class Solution {
public:
    string tree2str(TreeNode* root) {
        string tree;
        if (!root)
        {
            return tree;
        }
        tree += std::to_string(root->val);
        if (root->left == nullptr && root->right == nullptr)
        {
            return tree;
        }
        if (root->left || root->right)
        {
            tree += "(";
            tree += tree2str(root->left);
            tree += ")";
        }

        if (root->right)
        {
            tree += "(";
            tree += tree2str(root->right);
            tree += ")";
        }

        return tree;

    }
};